package com.sgy.zookeeper_api;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class CreateSession implements Watcher {

    // 允许等待一个线程
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    /*
        建立会话
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        /*
        * connectString：连接地址（ip:port）
        * sessionTimeout：会话超时时间
        * watcher：监听器
        * */
        ZooKeeper zooKeeper = new ZooKeeper("192.168.201.129:2181", 30000, new CreateSession());
        System.out.println(zooKeeper.getState());

        // 计数工具类CountDownLatch：让线程处于阻塞状态
        countDownLatch.await();

        System.out.println("客户端与服务端会话建立...");
    }

    /**
     * 回调方法：处理来自服务器端的watcher通知
     * @param watchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        // SyncConnected
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            // 解除主程序在CountDownLatch的等待阻塞
            countDownLatch.countDown();
        }
    }
}
